package com.alibaba.citrus.ots.application.report.ability.repository.impl;

import com.alibaba.citrus.ots.application.report.ability.repository.PlatformRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.BaselineBatchQueryPlatforms2Request;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByOutCodes2Request;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByOutCodes2Response;
import com.epoch.app.bcots.model.dto.OrganizationSDO;
import com.epoch.app.bcots.model.dto.PlatformSDO;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.crplatformenhance.model.dto.QueryAllCommercePlatformRequest;
import com.epoch.app.crplatformenhance.model.dto.QueryAllPlatformResponse;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.otsapplicationreportsdk.contants.OtsApplicationReportSdkConstants;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class PlatformRepositoryImpl implements PlatformRepository {
    private static Log log = Log.getLogger(PlatformRepositoryImpl.class);

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private CrUnifiedInventoryService otsUnifiedInventoryService;

    @Resource
    private CrPlatformEnhanceService otsPlatformEnhanceService;

    @Override
    public Set<String> getWarehouseByPlatFormCodes() {
        // 查询 1171 的组织id
//        OrganizationSDO organizationSDO = allocateOrderByCode("1171");
//        if (ObjectUtils.isEmpty(organizationSDO)) {
//            return new HashSet<>();
//        }
//
//        int start = 0;
//        int limit = 500;
//        OuiWareshouseIndexRequest request = OuiWareshouseIndexRequest.builder()
//                .start(start)
//                .limit(limit)
//                .type(CargoZoneTypeEnum.SHARE_CARGOZONE.getType())
//                .saleOrgId(organizationSDO.getId())
//                .build();
//        Result<List<OuiWarehouse>> listResult = otsUnifiedInventoryService.ouiWareshouseIndex(request);
//        if (ObjectUtils.isEmpty(listResult)) {
//            log.info("查询电商下仓库为空，入参：{}", JSON.toJSONString(request));
//            return new HashSet<>();
//        }
//        List<OuiWarehouse> warehouseList = listResult.getResult();
//        if (CollectionUtils.isEmpty(warehouseList)) {
//            log.info("查询电商下仓库为空，入参：{}", JSON.toJSONString(request));
//            return new HashSet<>();
//        }
//        int allPage = listResult.getTotal() / limit;
//        if(listResult.getTotal() % limit > 0){
//            allPage++;
//        }
//        for (int i = 1; i < allPage; i++) {
//            start = limit * i;
//            request.setStart(start);
//            Result<List<OuiWarehouse>> ouiWarehouseListResult = otsUnifiedInventoryService.ouiWareshouseIndex(request);
//            if (!ObjectUtils.isEmpty(ouiWarehouseListResult) && !CollectionUtils.isEmpty(ouiWarehouseListResult.getResult())) {
//                warehouseList.addAll(ouiWarehouseListResult.getResult());
//            }
//        }
//
//        Set<String> collect = warehouseList.stream().filter(o->!StringUtils.isEmpty(o.getEcPlatform())).map(OuiWarehouse::getEcPlatform).collect(Collectors.toSet());
//        collect.add(OtsApplicationReportSdkConstants.OTHER_PLATFORM_ID());
//        return collect;

        HashSet<String> platforms = new HashSet<>(geAllPlatformCodes());
        platforms.add(OtsApplicationReportSdkConstants.OTHER_PLATFORM_ID());
        return platforms;
    }

    @Override
    public List<String> geAllPlatformCodes(){
        List<String> resultList = new ArrayList<>();
        // 查询 1171 的组织id
        OrganizationSDO organizationSDO = allocateOrderByCode("1171");
        if (ObjectUtils.isEmpty(organizationSDO)) {
            return resultList;
        }
        QueryAllCommercePlatformRequest request = new QueryAllCommercePlatformRequest();
        request.setOrgId(organizationSDO.getId());
        Result<QueryAllPlatformResponse> result = otsPlatformEnhanceService.queryAllCommercePlatform(request);
        if (null==result|| null==result.getResult()||org.apache.commons.collections4.CollectionUtils.isEmpty(result.getResult().getPlatfromCodes())){
            return resultList;
        }
        List<String> platformCodes = result.getResult().getPlatfromCodes();
        BaselineBatchQueryPlatforms2Request baselineBatchQueryPlatforms2Request = new BaselineBatchQueryPlatforms2Request();
        baselineBatchQueryPlatforms2Request.setPlatformCodes(platformCodes);
        Result<List<PlatformSDO>> listResult = baseDataService.baselineBatchQueryPlatforms2(baselineBatchQueryPlatforms2Request);

        if (null==listResult||org.apache.commons.collections4.CollectionUtils.isEmpty(listResult.getResult())){
            return resultList;
        }
        resultList=listResult.getResult().stream().map(PlatformSDO::getPlatformId).collect(Collectors.toList());


        return resultList;
    }

    @Override
    public Map<String,String> geAllPlatformIdCodeMap(){

        Map<String,String> resultList = new HashMap<>();
        // 查询 1171 的组织id
        OrganizationSDO organizationSDO = allocateOrderByCode("1171");
        if (ObjectUtils.isEmpty(organizationSDO)) {
            return resultList;
        }
        QueryAllCommercePlatformRequest request = new QueryAllCommercePlatformRequest();
        request.setOrgId(organizationSDO.getId());
        Result<QueryAllPlatformResponse> result = otsPlatformEnhanceService.queryAllCommercePlatform(request);
        if (null==result|| null==result.getResult()||org.apache.commons.collections4.CollectionUtils.isEmpty(result.getResult().getPlatfromCodes())){
            return resultList;
        }
        List<String> platformCodes = result.getResult().getPlatfromCodes();
        BaselineBatchQueryPlatforms2Request baselineBatchQueryPlatforms2Request = new BaselineBatchQueryPlatforms2Request();
        baselineBatchQueryPlatforms2Request.setPlatformCodes(platformCodes);
        Result<List<PlatformSDO>> listResult = baseDataService.baselineBatchQueryPlatforms2(baselineBatchQueryPlatforms2Request);

        if (null==listResult||org.apache.commons.collections4.CollectionUtils.isEmpty(listResult.getResult())){
            return resultList;
        }
        resultList=listResult.getResult().stream().collect(Collectors.toMap(PlatformSDO::getPlatformId,PlatformSDO::getPlatformCode));

        return resultList;
    }


    @Override
    public Map<String,String> geAllPlatformIdNameMap(){

        Map<String,String> resultList = new HashMap<>();
        resultList.put(OtsApplicationReportSdkConstants.OTHER_PLATFORM_ID(),OtsApplicationReportSdkConstants.OTHER_PLATFORM_NAME());
        // 查询 1171 的组织id
        OrganizationSDO organizationSDO = allocateOrderByCode("1171");
        if (ObjectUtils.isEmpty(organizationSDO)) {
            return resultList;
        }
        QueryAllCommercePlatformRequest request = new QueryAllCommercePlatformRequest();
        request.setOrgId(organizationSDO.getId());
        Result<QueryAllPlatformResponse> result = otsPlatformEnhanceService.queryAllCommercePlatform(request);
        if (null==result|| null==result.getResult()||org.apache.commons.collections4.CollectionUtils.isEmpty(result.getResult().getPlatfromCodes())){
            return resultList;
        }
        List<String> platformCodes = result.getResult().getPlatfromCodes();
        BaselineBatchQueryPlatforms2Request baselineBatchQueryPlatforms2Request = new BaselineBatchQueryPlatforms2Request();
        baselineBatchQueryPlatforms2Request.setPlatformCodes(platformCodes);
        Result<List<PlatformSDO>> listResult = baseDataService.baselineBatchQueryPlatforms2(baselineBatchQueryPlatforms2Request);

        if (null==listResult||org.apache.commons.collections4.CollectionUtils.isEmpty(listResult.getResult())){
            return resultList;
        }
        resultList=listResult.getResult().stream().collect(Collectors.toMap(PlatformSDO::getPlatformId,PlatformSDO::getPlatformName));

        return resultList;
    }

    /**
     * 根据 code 查询 组织
     *
     * @param code
     * @return
     */
    private OrganizationSDO allocateOrderByCode(String code) {
        BaselineGetOrganizationByOutCodes2Request request = BaselineGetOrganizationByOutCodes2Request.builder()
                .outCodes(Arrays.asList(code))
                .build();
        BaselineGetOrganizationByOutCodes2Response res = baseDataService.baselineGetOrganizationByOutCodes2(request);
        if (ObjectUtils.isEmpty(res)) {
            return null;
        }
        List<OrganizationSDO> result = res.getResult();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(result)) {
            return null;
        }
        return result.get(0);
    }
}
